package com.neusoft.hifly.attachment.publish.api;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.neusoft.hifly.attachment.publish.service.IReleaseService;
import com.neusoft.hifly.commons.exception.SystemErrorException;
import com.neusoft.hifly.core.pojo.ApiCode;
import com.neusoft.hifly.core.pojo.ApiResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * Title: 附件服务
 * <p>
 * Description: 服务发布 接口
 * <p>
 * Copyright: 2019
 * <p>
 * Company: 东软汉枫
 *
 * @author lh_neu
 * @version 1.0.0
 */
@CrossOrigin
@RestController
@RequestMapping("/api/v1/release")
@Api(value = "release-api", description = "服务发布接口")
public class ReleaseApi {
	@Autowired(required = false)
	private IReleaseService releaseService;

	/**
	 * 服务发布
	 *
	 * @param HttpServletRequest
	 *            request
	 * @return 是否成功过
	 */
	@ApiOperation("服务发布")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "organCode", value = "租户编码", dataType = "string", paramType = "query", required = true),
			@ApiImplicitParam(name = "datasourceLogicId", value = "数据源逻辑ID，为0时使用默认数据源", dataType = "long", paramType = "query", required = true),
			@ApiImplicitParam(name = "isUpgrade", value = "是否发布的升级脚本", dataType = "boolean", paramType = "query") })
	@GetMapping(value = "")
	public ApiResponse<?> release(final HttpServletRequest request) {
		final String organCode = StringUtils.trimToEmpty(request.getParameter("organCode"));
		final String datasourceLogicId = StringUtils.trimToEmpty(request.getParameter("datasourceLogicId"));
		final String isUpgradeStr = StringUtils.trimToEmpty(request.getParameter("isUpgrade"));

		if (StringUtils.isEmpty(organCode)) {
			return new ApiResponse<>(ApiCode.ERROR.getCode(), "参数错误!");
		}

		boolean isUpgrade = false;
		if (StringUtils.isNotEmpty(isUpgradeStr)) {
			isUpgrade = Boolean.parseBoolean(isUpgradeStr);
		}

		try {
			releaseService.release(organCode, Long.parseLong(datasourceLogicId), isUpgrade);
		} catch (final SystemErrorException e) {
			return new ApiResponse<>(e);
		}

		return new ApiResponse<>(ApiCode.SUCCESS.getCode(), "成功！");
	}
}
